// //index.js
// //获取应用实例
var app = getApp()
var uid = '';
var cata = false;
//logs.js
var util = require('../../utils/util.js');
var wxAuthFail = true;
Page({
  data: {
    toView: 'hash1',
    data:{},
    hasData:false,
    mTop:0,
    footer_curr:[
      "curr",''
    ],
    searchVal:"",
    // adImg:"http://img.artart.cn/app/images/guanggao.jpg",
    adImg: "",
    adLink: null,
    businessCardWidth:"300px",
    imgDomain: app.globalData.imgDomain,
    followmeList:false,
    categoryData:false,
    recommendData:false,
    newData:false,
    hotData: false,
    hasShare: false,
    uid: '',
    cata: false,
    isAuthUser: false, //默认非黄钻认证用户
    isShow: false
  },
  inputVal: function (e) {
    this.setData({
      searchVal: e.detail.value
    })
  },
  search: function () {
    wx.navigateTo({ url: "/pages/search/search?val=" + this.data.searchVal })
  },
  goHash (e) {
    let hash = e.currentTarget.dataset.hash
    this.setData({
      toView: hash
    })
  },
  changeCategory: function(e){
    var index = e.currentTarget.dataset.index;
    var cid = e.currentTarget.dataset.cid;
    var category = this.data.categoryData;
    if(!category[index].curr){
      this.showRecommend(cid);
      this.showNew(cid);
      this.showDataList(cid);
      this.showHot(cid);
      category[index].curr = true;
      for(var i=0;i<category.length;i++){
        if(i != index){
          category[i].curr = false;
        }
      }
      this.setData({
        categoryData:category
      });
    }
  },
  anchorTouchMove:function(e){
    var index = parseInt((e.changedTouches['0'].pageY - e.currentTarget.dataset.ptop) /20);
    if(this.oldIndex != index){
      this.oldIndex = index;
      var anchor = this.data.data;
      var i = 4;
      if(index == 0){
        this.setData({
          toView: "search"
        });
        return false;
      }else if(index == 1){
        this.setData({
          toView: "tuijian"
        });
        return false;
      }else if(index == 2){
        this.setData({
          toView: "zuixin"
        });
        return false;
      }else if(index == 3){
        this.setData({
          toView: "remen"
        });
        return false;
      }
      for(var key in anchor){
        if(i++ == index){
          this.setData({
            toView: key
          });
          return false;
        }
      }
    }
  },
  showRecommend: function(cateID){
    var that = this;
    var data = {
      "publickey": util.publiccode,
      "ac": "tongxunlu",
      "rec": 1
    }
    if(cateID) data.usercata = cateID;
    util.api({
      data: data,
      success: function(responseData){
        var data = responseData.data;
        var recommendData = [];
        if(!data.msg){
          for(var key in data){
            recommendData = recommendData.concat(data[key]);
          }
        }
        that.setData({
          recommendData:recommendData
        });
      }
    });
  },
  showNew: function(cateID){
    var that = this;
    var data = {
      "publickey": util.publiccode,
      "ac": "tongxunlu",
      "new": 1
    }
    if(cateID) data.usercata = cateID;
    util.api({
      data: data,
      success: function(responseData){
        var data = responseData.data;
        var newData = [];
        if(!data.msg){
          for(var key in data){
            newData = newData.concat(data[key]);
          }
        }
        that.setData({
          newData:newData
        });
      }
    });
  },
  showHot: function(cateID){
    var that = this;
    var data = {
      "publickey": util.publiccode,
      "ac": "tongxunlu",
      "hot": 1
    }
    if(cateID) data.usercata = cateID;
    util.api({
      data: data,
      success: function(responseData){
        var data = responseData.data;
        console.log(data);
        var hotData = [];
        if(!data.msg){
          for(var key in data){
            hotData = hotData.concat(data[key]);
          }
        }
        that.setData({
          hotData:hotData
        });
      }
    });
  },

  goAdLinkPage: function(){
    if (this.data.adLink){
      console.log("adLink:", this.data.adLink);
      wx.navigateTo({ url: this.data.adLink });
    } else {
      wx.navigateTo({ url: "/pages/hongbao/hongbao?shareuid=9339&hongbaoid=13" });
    }
  },

  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      // wx.reLaunch({ //用这个会报错fail can not invoke relaunch in background
      wx.redirectTo({
        url: '/pages/mail-list/mail-list'
      })
    // } else {
    //   wx.redirectTo({
    //     url: '/pages/mail-list/mail-list'
    //   })
    }
  },

  goCardListPage: function(e){
    if(wxAuthFail) {
      app.reAuthorize(this.reGetUserInfo);
    } else {
      this.goAtherPage(e);
    }
  },
  goAtherPage: function(e){
      var url = e.currentTarget.dataset.link;
      wx.navigateTo({url: url})
  },
  goAtherPageRedirect: function(e){
      var url = e.currentTarget.dataset.link;
      wx.redirectTo({url: url})
  },
  onLoad: function(options){    
    var that = this;
    var inviteuid = options.inviteuid;
    
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "wxcheck"
      },
      success: function (responseData) {
        that.setData({
          isShow: responseData.data.isShow
        });
      }
    });

    //调用应用实例的方法获取全局数据
    app.LoginUserInfo(function(res){
      console.log("userInfo:", res);  
      wxAuthFail = res == -1;//用户拒绝授权
      if (!wxAuthFail){
      //更新数据  
      uid = res.uid;
      cata = (parseInt(res.usercata) > 0) ? true : false;
      var authStr = res.auth;
      var isAuth = false;
      if (util.isString(authStr)){
        isAuth = authStr.indexOf("15") >= 0 ? true : false;
      }
      if (inviteuid && !cata) {
        this.setData({
          uid: uid,
          cata: cata,
          isAuthUser: isAuth,
          hasShare: true
        });
      } else {
        that.setData({
          uid: uid,
          cata: cata,
          isAuthUser: isAuth
        });
      }
      
      util.api({
        data: {
          "uid": uid,
          "publickey": util.publiccode,
          "ac": "followmelist"
        },
        success: function(responseData){
          if(!responseData.data.msg){
            that.setData({
              followmeList:responseData.data
            });
          }
        }
      });

      }

    }, inviteuid);

    //获取广告图片链接 和 广告跳转 链接
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "xcxhongbaobanner"
      },
      success: function (responseData) {
        console.log("xcxhongbaobanner: ", responseData);
        if (responseData.statusCode == 200 && !responseData.data.msg) {
          var res = responseData.data
          that.setData({
            adImg: res.image,
            adLink: res.link
          }); 
        }
      }
    });

    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "usercata"
      },
      success: function(responseData){
        for(var i=0;i<responseData.data.length;i++ ){
          responseData.data[i].curr=false;
          responseData.data[i].index = i;
          if(responseData.data[i].user_category_id == 98)
            responseData.data[i].curr=true;
        }
        that.setData({
          categoryData:responseData.data
        });
      }
    });
    this.showRecommend(98);
    this.showNew(98);
    this.showHot(98);
    this.showDataList(98);
  },
  showDataList: function(cateID){
    var that = this;
    var listKey = 'yiyoulu';
    var listStorage = wx.getStorageSync(listKey);
    listStorage = null;
    var data = {
      "publickey": util.publiccode,
      "ac": "tongxunlu"
    };
    if(cateID) data.usercata = cateID;
    if (listStorage) {
      that.setData({
        hasData: true,
        data: listStorage
      })
    } else {
      util.api({
        data: data,
        success: function (responseData) {
          //wx.setStorageSync(listKey, responseData.data);
          var num = ((that.data.recommendData && that.data.recommendData.length > 0)?1:0) +
                    ((that.data.newData && that.data.newData.length > 0)?1:0) +
                    ((that.data.hotData && that.data.hotData.length > 0)?1:0)
          var i = 1 + num;
          var resData = responseData.data;
          var data = {};
          var hasData = false;
          if(!resData.msg){
            hasData = true;
            for(var key in resData){
              i++;
            }
            data = resData;
          }
          
          console.log(responseData);
          wx.getSystemInfo({
            success: function(res) {
                    that.setData({
                      hasData: hasData,
                      data: data,
                      mTop: (res.windowHeight-(i*20))/2,
                      businessCardWidth:(res.windowWidth-71)+"px"
                    });
            }
          })
        }
      });
    }
  },
  onReady: function(){
   
  },

  onShow: function() {
    var that = this;
    app.LoginUserInfo(function (res) {
      wxAuthFail = res == -1;
      if (!wxAuthFail) {
      //更新数据      
      uid = res.uid;
      cata = (parseInt(res.usercata) > 0) ? true : false;
      var authStr = res.auth;
      var isAuth = false;
      if (util.isString(authStr)) {
        isAuth = authStr.indexOf("15") >= 0 ? true : false;
      }
      that.setData({
        uid: uid,
        cata: cata,
        isAuthUser: isAuth
      });
      }
    });
  },
  //下拉刷新
  onPullDownRefresh: function(){
    console.log('refresh...');
    wx.stopPullDownRefresh()
  },
  //页面分享
  onShareAppMessage: function () {
    return app.sharePage('', uid);
  },

  //保存formId
  submitFormId: function (e) {
    console.log("formId: ", e.detail.formId);
    app.saveFormId(e.detail.formId);
  },


  goYTX_miniProgram:function(){
    // wx.showToast({
    //   title: '到艺天下小程序',
    // })
    wx.navigateToMiniProgram({
      appId: 'wx9a963256f88b06ed',
      path: 'pages/index/index?id=' + this.data.uid,
      extarData: {
        open: 'happy'
      },
      envVersion: 'release',
      success(res) {
        // wx.showToast({
        //   title: '打开成功',
        // })
      },
      fail(res){
        // wx.showToast({
        //   title: '打开失败' + JSON.stringify(res),
        // })
      }
    }) 
  }
   
})